package com.apobates.forum.thrones.admin.controller;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.entity.TopicCategory;
import com.apobates.forum.core.service.BoardTopicCategoryIndexService;
import com.apobates.forum.core.service.TopicCategoryService;
import com.apobates.forum.thrones.admin.controller.form.TopicCategoryForm;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
import javax.validation.Valid;
import org.springframework.validation.BindingResult;

/**
 * 话题类型控制器
 *
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/topic/category")
public class AdminTopicCategoryController {
    @Autowired
    private TopicCategoryService topicCategoryService;
    @Autowired
    private BoardTopicCategoryIndexService boardTopicCategoryIndexService;
    @Value("${site.pageSize}")
    private int pageSize;
    
    @GetMapping(path = "/")
    public String listPage(@RequestParam(value = "p", required = false, defaultValue = "1") int page, HttpServletRequest request, Model model) {
        FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/topic/category/").addPageSize("number", pageSize);
        Pageable pr = new PageRequest(page, fpbuild.getPageSize());
        Page<TopicCategory> rs = topicCategoryService.getAll(pr);
        model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
        model.addAttribute("pageData", fpbuild.toPageData(pr, rs.getTotalElements()));
        return "admin/topic_category/index";
    }
    //增加|编辑
    @GetMapping(path = "/edit")
    public String editForm(
            @RequestParam(name = "id", required = false, defaultValue = "0") int id,
            HttpServletRequest request,
            Model model) {
        TopicCategoryForm form = new TopicCategoryForm();
        TopicCategory tc = topicCategoryService.get(id).orElse(new TopicCategory());
        form.setNames(tc.getNames());
        form.setEnvalue(tc.getValue());
        form.setStatus(tc.isStatus());
        form.setRecord(id);
        model.addAttribute("form", form);
        return "admin/topic_category/edit";
    }
    
    @PostMapping(path = "/edit")
    public String editAction(
            HttpServletRequest request,
            @Valid @ModelAttribute("form") TopicCategoryForm form,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            return "admin/topic_category/edit";
        }
        TopicCategory tc = new TopicCategory();
        tc.setNames(form.getNames());
        tc.setValue(form.getEnvalue());
        tc.setStatus(form.getBooleanStatus());
        //
        boolean symbol;
        if (form.isUpdate()) {
            symbol = topicCategoryService.edit(form.getIntegerRecord(), tc).orElse(false);
        } else {
            symbol = topicCategoryService.create(tc.getNames(), tc.getValue(), tc.isStatus()).isPresent();
        }
        if (symbol) {
            return "redirect:/topic/category/";
        }
        model.addAttribute("errors", form.getActionTitle() + "话题类型操作失败");
        model.addAttribute("form", form);
        return "admin/topic_category/edit";
    }
    
    //删除
    @PostMapping(path = "/remove", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removeTagAction(
            @RequestParam("id") int categoryId,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->topicCategoryService.remove(categoryId)).success("话题类型删除成功").error("操作失败");
    }
    
    //所有可用的
    @GetMapping(path = "/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, String> getAllBoardForJson(
            HttpServletRequest request,
            Model model) {
        return topicCategoryService.getAllUsed().collect(Collectors.toMap(TopicCategory::getValue, TopicCategory::getNames));
    }
    //指定版块可以发布的话题类型
    @GetMapping(path = "/list.json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TreeMap<String, String> getBoardTopicCategories(
            @RequestParam("volumes") int boardGroupId,
            @RequestParam("board") long boardId,
            HttpServletRequest request,
            Model model) {
        TreeSet<TopicCategory> categories = new TreeSet<>();
        if (boardGroupId >= 0 && boardId > 0) {
            Supplier<TreeSet<TopicCategory>> supplier = () -> new TreeSet<>(Comparator.comparingLong(TopicCategory::getId));
            categories = boardTopicCategoryIndexService.getAllByBoardTopicCategories(boardGroupId, boardId).collect(Collectors.toCollection(supplier));
        } else {
            categories.add(TopicCategory.empty()); //java.lang.ClassCastException: com.apobates.forum.core.entity.TopicCategory cannot be cast to java.lang.Comparable
        }
        return categories.stream().collect(Collectors.toMap(TopicCategory::getValue, TopicCategory::getNames, (oldVal, newVal) -> newVal, TreeMap::new));
    }
}